﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Xml;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;

namespace InfoJetSoft.Service.Worker
{
	
	class XSNViewFormatButtonWorker
	{
		
		public static void formatButton(HttpContext httpContext, Manifest manifest,View view)
		{
            //CID 1422 //2012.11.14 //Begin
            List<XmlElement> pictureButtonElementList = new List<XmlElement>();
            //CID 1422 //2012.11.14 //End
            //CID 1503 //2012.12.20 //Begin
            List<XmlElement> signatureLineElementList = new List<XmlElement>();
            //CID 1503 //2012.12.20 //End

			XmlElement root = view.Doc.DocumentElement;
            //CID 0613 //2010.7.10 //button
			string inputFilter = "//input | //button";
			string xctNameFullName = NamespaceUtil.toFullName(view.XdPrefix, JetConstant.XD_xctname);
			string actionFullName = NamespaceUtil.toFullName(view.XdPrefix, JetConstant.XD_action); 
			string ctrlIdFullName = NamespaceUtil.toFullName(view.XdPrefix, JetConstant.XD_CtrlId);

			XmlNodeList inputElementList = DOMUtil.selectNodes(root, inputFilter, 0, view.NsResolver);
			for (int i = 0; i < inputElementList.Count; i ++ ){
				XmlElement inputElement = (XmlElement) inputElementList[ i ];
				string xctName = inputElement.GetAttribute( xctNameFullName );
                //CID 0613 //2010.7.10 //PictureButton
				if( xctName.Length > 0 && ( xctName.Equals( "Button" ) || xctName.Equals( "PictureButton" ) ) )
                {
					string action = inputElement.GetAttribute( actionFullName );
					if( action.Length > 0 && action.Equals( "query" ) ){
						inputElement.SetAttribute( "onclick", "javascript:InfoJet_DoQuery(this);" );
						inputElement.SetAttribute( JetConstant.HTML_id, "InfoJet_Control" + i );
					}
					if( action.Length > 0 && action.Equals( "refresh" ) ){
						inputElement.SetAttribute( "onclick", "javascript:InfoJet_DoRefresh(this);" );
						inputElement.SetAttribute( JetConstant.HTML_id, "InfoJet_Control" + i );
					}
					if( action.Length > 0 && action.Equals( "new" ) )
					{
						inputElement.SetAttribute( "onclick", "javascript:InfoJet_DoNew(this);" );
						inputElement.SetAttribute( JetConstant.HTML_id, "InfoJet_Control" + i );
					}
					if( action.Length > 0 && action.Equals( "submit" ) ){
						if( manifest.Submit != null )
						{
							//如果是SubmitToHost，直接在客户端submit，调用InfoJet_SubmitToHost()。
                            if( manifest.Submit.SubmitToHostAdapter != null)
							{
                                //CID 1134 //2012.03.16 //Begin
                                if (ConfigUtil.EnableSubmitToHostEvent())
                                {
                                    inputElement.SetAttribute("onclick", "javascript:InfoJet_DoSubmit(this);");
                                }
                                else
                                {
                                    inputElement.SetAttribute("onclick", "javascript:InfoJet_SubmitToHost(this);");
                                }
                                //CID 1134 //2012.03.16 //End
							}
							else
							{
								inputElement.SetAttribute( "onclick", "javascript:InfoJet_DoSubmit(this);" );
							}
							inputElement.SetAttribute( JetConstant.HTML_id, "InfoJet_Control" + i );
						}
					}
					if( action.Length == 0 ){
						//这里不加ctrlId.length > 0的判断,是为了保持InfoJet_Control[i]的连续.
						inputElement.SetAttribute( JetConstant.HTML_id, "InfoJet_Control" + i );
						
						string ctrlId = inputElement.GetAttribute( ctrlIdFullName );
						
						//在InfoJet_DoButton中,如果没有ctrlId函数就会返回,不提交页面.
						inputElement.SetAttribute( "onclick", "javascript:InfoJet_DoButton(this);" );
						
						//将Html button元素添加到ruleButton.HtmlButtonList中,在XSNManifestRuleButtonRuleSetParseWorker中使用.
						//因为这时RuleButton.RuleSet为null,所以要等到XSNManifestRuleButtonRuleSetParseWorker中处理
						//(判断按钮规则中是否要提交表单,如果提交表单则设置HtmlButton的Submit_Button属性为true.).
						if( ctrlId != null && ctrlId.Length > 0 )
						{
							foreach( RuleButton ruleButton in view.RuleButtonList )
							{
								if( ctrlId.Equals( ruleButton.ButtonName ) )
								{
									//有可能多个按钮有同一个ctrlId,所以使用一个List存储HtmlButton.
									if( ruleButton.HtmlButtonList == null )
									{
										ruleButton.HtmlButtonList = new ArrayList();
									}
									ruleButton.HtmlButtonList.Add( inputElement );
								}
							}
						}
					}
                    //CID 0618 //2010.07.05 //Begin
					//CID 0114 //2008.09.11 //Begin
                    formatBackgroundImage(httpContext, manifest, inputElement);
					//CID 0114 //2008.09.11 //End
                    //CID 0618 //2010.07.05 //End
					//CID 0347 //2009.07.13 //Begin
					inputElement.SetAttribute( "onmousedown", "javascript:InfoJet_OnButtonMouseDown(event, this);" );
					inputElement.SetAttribute( "onfocus", "javascript:InfoJet_OnButtonFocus(event, this);" );
					//CID 0347 //2009.07.13 //End
                    //CID 0613 //2010.07.10 //Begin
                    if (inputElement.Name.ToLower().Equals("button"))
                    {

                        XmlElement imgElement = (XmlElement)inputElement.SelectSingleNode("img");
                        if (imgElement != null)
                        {
                            string imgSrc = imgElement.GetAttribute( "src" );
                            if (imgSrc == null || imgSrc.Length <= 0 || imgSrc.IndexOf("res://infopath.exe") >= 0)
                            {
                                imgElement.SetAttribute("src", manifest.ImageUri.PictureButtonPlaceholder);
                            }

                            XmlAttribute hoverSrcAttr = imgElement.GetAttributeNode( NamespaceUtil.toFullName( view.XdPrefix, "HoverSRC" ) );
                            if (hoverSrcAttr != null && hoverSrcAttr.Value != null && hoverSrcAttr.Value.Length > 0)
                            {
                                hoverSrcAttr.Value = ResourceFileUtil.getResourceFileUrl(view.Manifest, hoverSrcAttr.Value);
                                inputElement.SetAttribute("onmouseover", "InfoJet_OnPictureButtonMouseOver(this);");
                                inputElement.SetAttribute("onmouseout", "InfoJet_OnPictureButtonMouseOut(this);");
                            }
                            //CID 1422 //2012.11.14 //Begin
                            pictureButtonElementList.Add(inputElement);
                            imgElement.SetAttribute("border", "0");
                            string style = imgElement.GetAttribute("style");
                            if (style != null && style.Length > 0)
                            {
                                style = style.Replace("WIDTH: 100%;", "");
                                imgElement.SetAttribute("style", style);
                            }
                            //CID 1422 //2012.11.14 //End
                        }
                    }
                }
                //CID 0613 //2010.07.10 //End
                //CID 1503 //2012.12.20 //Begin
                if (xctName.Length > 0 && xctName.Equals("SignatureLine"))
                {
                    signatureLineElementList.Add(inputElement);
                }
                //CID 1503 //2012.12.20 //End
			}

            //CID 1422 //2012.11.14 //Begin
            foreach (XmlElement pictureButtonElement in pictureButtonElementList)
            {
                pictureButtonElement.SetAttribute("href", "javascript:void(0);");
                string style = pictureButtonElement.GetAttribute("style");
                if (style == null)
                {
                    style = "";
                }
                pictureButtonElement.SetAttribute("style", style + ";cursor:default;");
                DOMUtil.renameElementName(pictureButtonElement, "a");
            }
            //CID 1422 //2012.11.14 //End

            //CID 1503 //2012.12.20 //Begin
            foreach (XmlElement signatureLineElement in signatureLineElementList)
            {
                formatSignatureLine(manifest, view, signatureLineElement, ctrlIdFullName);
            }
            //CID 1503 //2012.12.20 //End
		}

		//CID 0114 //2008.09.11 //Begin
		private static void formatBackgroundImage(HttpContext httpContext, Manifest manifest, XmlElement buttonElement )
		{
			string style = buttonElement.GetAttribute( "style" );
			if( style != null && style.Length > 0 )
			{
				int begin = style.IndexOf( "BACKGROUND-IMAGE: url(" );
				if( begin >= 0 )
				{
					begin = begin + "BACKGROUND-IMAGE: url(".Length;
					int end = style.IndexOf( ")", begin );
					if( end > 0 )
					{
						string url = style.Substring( begin, end - begin );

                        //CID 0618 //2010.07.05 //Begin
                        string resourceUrl = null;
                        //CID 0114 //2008.09.11 //Begin
                        string staticResourcePath = ConfigUtil.StaticResourcePath(httpContext);
                        //CID 0114 //2008.09.11 //End
                        if (staticResourcePath != null)
                        {
                            //CID 0618 //2011.05.29 //Begin
                            if (staticResourcePath.EndsWith("/"))
                            {
                                resourceUrl = staticResourcePath + url;
                            }
                            else
                            {
                                resourceUrl = staticResourcePath + "/" + url;
                            }
                            //CID 0618 //2011.05.29 //End
                        }
                        else
                        {
                            resourceUrl = ResourceFileUtil.getResourceFileUrl(manifest, url);
                        }
                        //CID 0618 //2010.07.05 //End

						style = style.Replace( "BACKGROUND-IMAGE: url(" + url + ")", "BACKGROUND-IMAGE: url(" + resourceUrl + ")" );
						buttonElement.SetAttribute( "style", style );
					}
				}
			}
		}
		//CID 0114 //2008.09.11 //End

        //CID 1503 //2012.12.20 //Begin
        private static void formatSignatureLine(Manifest manifest, View view, XmlElement inputElement, string ctrlIdFullName)
        {
            string ctrlId = inputElement.GetAttribute(ctrlIdFullName);
            if (view.SignatureLines != null)
            {
                foreach (SignatureLine signatureLine in view.SignatureLines)
                {
                    if (signatureLine.Name.Equals(ctrlId))
                    {
                        XmlElement buttonElement = DOMUtil.renameElementName(inputElement, "button");

                        buttonElement.SetAttribute("dsig_block", signatureLine.SignedDataBlock);
                        buttonElement.SetAttribute("ctrl_id", ctrlId);
                        buttonElement.SetAttribute("view_name", view.Name);
                        
                        XmlDocument templateDoc = new XmlDocument();
                        //CID 2079 //2014.01.08 //Begin
                        string slTemplate = SignatureLineTemplate.Replace("$ctrl_id$", ctrlId);
                        templateDoc.LoadXml(slTemplate);
                        //CID 2079 //2014.01.08 //End
                        XmlElement templateElement = view.Doc.ImportNode(templateDoc.DocumentElement, true) as XmlElement;
                        buttonElement.AppendChild(templateElement);
                        
                        break;
                    }
                }
            }
        }
        //CID 1503 //2012.12.20 //End

        //CID 1503 //2012.12.22 //Begin
        //CID 2079 //2014.01.08 //Begin
        private static string SignatureLineTemplate = @"
<xsl:choose xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
    <xsl:when test='xdXDocument:HasSignatureLine(&quot;$ctrl_id$&quot;)=&quot;true&quot;'>
        <xsl:attribute name='onclick'>InfoJet_ShowSignatureDetails(this);</xsl:attribute>
        <xsl:for-each select='xdXDocument:GetSignatureLineElement(&quot;$ctrl_id$&quot;)'>
            <xsl:attribute name='dsig_id'>
                <xsl:value-of select='xdExtension:GetJetId(.)' />
            </xsl:attribute>
		    <xsl:choose>
                <xsl:when test='xdXDocument:GetNamedNodeProperty(., &quot;IsValidSignature&quot;, &quot;false&quot;) = &quot;true&quot;'>
                    <div style='font-weight:bold;white-space: nowrap;font-style:italic;margin:2px;'>
                        Signed by 
                        <xsl:value-of select='xdXDocument:GetNamedNodeProperty(., &quot;SignedBy&quot;, &quot;???&quot;)'/>
                    </div>
                    <div style='white-space: nowrap;font-style:italic;margin:2px;'>
                        <xsl:value-of select='xdXDocument:GetNamedNodeProperty(., &quot;SignedOn&quot;, &quot;???&quot;)'/>
                    </div>
                </xsl:when>
                <xsl:otherwise>
                    <div style='color:red;white-space: nowrap;font-style:italic;margin:2px;'>
                        There is a problem with this signature. 
                    </div>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>
    </xsl:when>
    <xsl:otherwise> 
        <xsl:attribute name='onclick'>InfoJet_OnSignatureButtonClick(event, this, true);</xsl:attribute>
        <div>Click here to sign</div>
    </xsl:otherwise>
</xsl:choose>
";
        //CID 2079 //2014.01.08 //End
        //CID 1503 //2012.12.22 //End
		
	}
}